pax_global_header00006660000000000000000000000064145740637630014531gustar00rootroot0000000000000052 comment=12b33b275e12e22cc3f772836d13043cb774ebe3 terminado-0.18.1/000077500000000000000000000000001457406376300136025ustar00rootroot00000000000000terminado-0.18.1/.git-blame-ignore-revs000066400000000000000000000001561457406376300177040ustar00rootroot00000000000000# Use auto formatters: https://github.com/jupyter/terminado/pull/149 cc8a42b89ecac8ee9e3e6bfffd0ace3fde6788e0 terminado-0.18.1/.github/000077500000000000000000000000001457406376300151425ustar00rootroot00000000000000terminado-0.18.1/.github/dependabot.yml000066400000000000000000000005071457406376300177740ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" groups: actions: patterns: - "*" - package-ecosystem: "pip" directory: "/" schedule: interval: "weekly" groups: actions: patterns: - "*" terminado-0.18.1/.github/workflows/000077500000000000000000000000001457406376300171775ustar00rootroot00000000000000terminado-0.18.1/.github/workflows/enforce-label.yml000066400000000000000000000005001457406376300224130ustar00rootroot00000000000000name: Enforce PR label on: pull_request: types: [labeled, unlabeled, opened, edited, synchronize] jobs: enforce-label: runs-on: ubuntu-latest permissions: pull-requests: write steps: - name: enforce-triage-label uses: jupyterlab/maintainer-tools/.github/actions/enforce-label@v1 terminado-0.18.1/.github/workflows/prep-release.yml000066400000000000000000000032311457406376300223050ustar00rootroot00000000000000name: "Step 1: Prep Release" on: workflow_dispatch: inputs: version_spec: description: "New Version Specifier" default: "next" required: false branch: description: "The branch to target" required: false post_version_spec: description: "Post Version Specifier" required: false silent: description: "Set a placeholder in the changelog and don't publish the release." required: false type: boolean since: description: "Use PRs with activity since this date or git reference" required: false since_last_stable: description: "Use PRs with activity since the last stable git tag" required: false type: boolean jobs: prep_release: runs-on: ubuntu-latest permissions: contents: write steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Prep Release id: prep-release uses: jupyter-server/jupyter_releaser/.github/actions/prep-release@v2 with: token: ${{ secrets.GITHUB_TOKEN }} version_spec: ${{ github.event.inputs.version_spec }} silent: ${{ github.event.inputs.silent }} post_version_spec: ${{ github.event.inputs.post_version_spec }} target: ${{ github.event.inputs.target }} branch: ${{ github.event.inputs.branch }} since: ${{ github.event.inputs.since }} since_last_stable: ${{ github.event.inputs.since_last_stable }} - name: "** Next Step **" run: | echo "Optional): Review Draft Release: ${{ steps.prep-release.outputs.release_url }}" terminado-0.18.1/.github/workflows/publish-changelog.yml000066400000000000000000000016401457406376300233160ustar00rootroot00000000000000name: "Publish Changelog" on: release: types: [published] workflow_dispatch: inputs: branch: description: "The branch to target" required: false jobs: publish_changelog: runs-on: ubuntu-latest environment: release steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: actions/create-github-app-token@v1 id: app-token with: app-id: ${{ vars.APP_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - name: Publish changelog id: publish-changelog uses: jupyter-server/jupyter_releaser/.github/actions/publish-changelog@v2 with: token: ${{ steps.app-token.outputs.token }} branch: ${{ github.event.inputs.branch }} - name: "** Next Step **" run: | echo "Merge the changelog update PR: ${{ steps.publish-changelog.outputs.pr_url }}" terminado-0.18.1/.github/workflows/publish-release.yml000066400000000000000000000034061457406376300230110ustar00rootroot00000000000000name: "Step 2: Publish Release" on: workflow_dispatch: inputs: branch: description: "The target branch" required: false release_url: description: "The URL of the draft GitHub release" required: false steps_to_skip: description: "Comma separated list of steps to skip" required: false jobs: publish_release: runs-on: ubuntu-latest environment: release permissions: id-token: write steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: actions/create-github-app-token@v1 id: app-token with: app-id: ${{ vars.APP_ID }} private-key: ${{ secrets.APP_PRIVATE_KEY }} - name: Populate Release id: populate-release uses: jupyter-server/jupyter_releaser/.github/actions/populate-release@v2 with: token: ${{ steps.app-token.outputs.token }} branch: ${{ github.event.inputs.branch }} release_url: ${{ github.event.inputs.release_url }} steps_to_skip: ${{ github.event.inputs.steps_to_skip }} - name: Finalize Release id: finalize-release uses: jupyter-server/jupyter_releaser/.github/actions/finalize-release@v2 with: token: ${{ steps.app-token.outputs.token }} release_url: ${{ steps.populate-release.outputs.release_url }} - name: "** Next Step **" if: ${{ success() }} run: | echo "Verify the final release" echo ${{ steps.finalize-release.outputs.release_url }} - name: "** Failure Message **" if: ${{ failure() }} run: | echo "Failed to Publish the Draft Release Url:" echo ${{ steps.populate-release.outputs.release_url }} terminado-0.18.1/.github/workflows/test.yml000066400000000000000000000107601457406376300207050ustar00rootroot00000000000000name: Tests on: push: branches: ["main"] pull_request: schedule: - cron: "0 8 * * *" concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} cancel-in-progress: true jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] python-version: ["3.8", "3.12"] include: - os: windows-latest python-version: "3.10" - os: ubuntu-latest python-version: "pypy-3.9" - os: ubuntu-latest python-version: "3.11" - os: macos-latest python-version: "3.9" steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Run the tests run: | hatch run cov:test || hatch run test:test --lf - uses: jupyterlab/maintainer-tools/.github/actions/upload-coverage@v1 coverage: runs-on: ubuntu-latest needs: - test steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/report-coverage@v1 with: fail_under: 75 check_release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Install Dependencies run: | pip install -e . - name: Check Release uses: jupyter-server/jupyter_releaser/.github/actions/check-release@v2 with: token: ${{ secrets.GITHUB_TOKEN }} test_minimum_versions: name: Test Minimum Versions timeout-minutes: 20 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 with: dependency_type: minimum - name: Run the unit tests run: | hatch run test:nowarn || hatch run test:nowarn --lf test_prereleases: name: Test Prereleases runs-on: ubuntu-latest timeout-minutes: 20 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 with: dependency_type: pre - name: Run the tests run: | hatch run test:nowarn || hatch run test:nowarn --lf make_sdist: name: Make SDist runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/make-sdist@v1 test_sdist: runs-on: ubuntu-latest needs: [make_sdist] name: Install from SDist and Test timeout-minutes: 20 steps: - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/test-sdist@v1 check_links: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/check-links@v1 jupyter_server_terminals: runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - uses: jupyterlab/maintainer-tools/.github/actions/downstream-test@v1 with: package_name: jupyter_server_terminals test_lint: name: Test Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - name: Run Linters run: | hatch run typing:test hatch run lint:build pipx run interrogate -v . pipx run doc8 --max-line-length=200 --ignore-path=doc/index.rst docs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1 - run: hatch run docs:build tests_check: # This job does nothing and is only used for the branch protection if: always() needs: - coverage - test_lint - docs - check_release - jupyter_server_terminals - test_minimum_versions - test_prereleases - check_links - test_sdist runs-on: ubuntu-latest steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: jobs: ${{ toJSON(needs) }} terminado-0.18.1/.gitignore000066400000000000000000000002411457406376300155670ustar00rootroot00000000000000.DS_Store *~ *.pyc *.prev *.sav *.old *.pem .cache/ README.html build/* dist/* MANIFEST terminado.egg-info/* BAK IGNORE ORIG SUBMIT doc/_build/ doc/changelog.md terminado-0.18.1/.pre-commit-config.yaml000066400000000000000000000041001457406376300200560ustar00rootroot00000000000000ci: autoupdate_schedule: monthly autoupdate_commit_msg: "chore: update pre-commit hooks" repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-case-conflict - id: check-ast - id: check-docstring-first - id: check-executables-have-shebangs - id: check-added-large-files - id: check-case-conflict - id: check-merge-conflict - id: check-json - id: check-toml - id: check-yaml - id: debug-statements - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/python-jsonschema/check-jsonschema rev: 0.27.4 hooks: - id: check-github-workflows - repo: https://github.com/executablebooks/mdformat rev: 0.7.17 hooks: - id: mdformat - repo: https://github.com/pre-commit/mirrors-prettier rev: "v4.0.0-alpha.8" hooks: - id: prettier types_or: [yaml, html, json] - repo: https://github.com/adamchainz/blacken-docs rev: "1.16.0" hooks: - id: blacken-docs additional_dependencies: [black==23.7.0] - repo: https://github.com/codespell-project/codespell rev: "v2.2.6" hooks: - id: codespell args: ["-L", "incase"] - repo: https://github.com/pre-commit/mirrors-mypy rev: "v1.8.0" hooks: - id: mypy files: "^terminado" stages: [manual] args: ["--install-types", "--non-interactive"] additional_dependencies: ["tornado", "ptyprocess"] - repo: https://github.com/pre-commit/pygrep-hooks rev: "v1.10.0" hooks: - id: rst-backticks - id: rst-directive-colons - id: rst-inline-touching-normal - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.2.0 hooks: - id: ruff types_or: [python, jupyter] args: ["--fix", "--show-fixes"] - id: ruff-format types_or: [python, jupyter] - repo: https://github.com/scientific-python/cookie rev: "2024.01.24" hooks: - id: sp-repo-review additional_dependencies: ["repo-review[cli]"] terminado-0.18.1/.readthedocs.yaml000066400000000000000000000003521457406376300170310ustar00rootroot00000000000000version: 2 sphinx: configuration: doc/conf.py python: install: # install itself with pip install . - method: pip path: . extra_requirements: - docs build: os: ubuntu-22.04 tools: python: "3.11" terminado-0.18.1/CHANGELOG.md000066400000000000000000000600221457406376300154130ustar00rootroot00000000000000# Changelog ## 0.18.1 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.18.0...6140cab7db7d7e0a0fa807bfcdb4db5bea1005e0)) ### Maintenance and upkeep improvements - Update Release Scripts [#238](https://github.com/jupyter/terminado/pull/238) ([@blink1073](https://github.com/blink1073)) - chore: update pre-commit hooks [#237](https://github.com/jupyter/terminado/pull/237) ([@pre-commit-ci](https://github.com/pre-commit-ci)) - Update pre-commit and ruff config [#235](https://github.com/jupyter/terminado/pull/235) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2023-11-10&to=2024-03-12&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2023-11-10..2024-03-12&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Apre-commit-ci+updated%3A2023-11-10..2024-03-12&type=Issues) ## 0.18.0 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.17.1...e1a98d4078cf72e7721d46c20d78daf813a297ef)) ### Maintenance and upkeep improvements - Remove py37 support [#233](https://github.com/jupyter/terminado/pull/233) ([@blink1073](https://github.com/blink1073)) - chore: update pre-commit hooks [#232](https://github.com/jupyter/terminado/pull/232) ([@pre-commit-ci](https://github.com/pre-commit-ci)) - Clean up lint handling [#231](https://github.com/jupyter/terminado/pull/231) ([@blink1073](https://github.com/blink1073)) - Use ruff format and fix docs warning [#230](https://github.com/jupyter/terminado/pull/230) ([@blink1073](https://github.com/blink1073)) - Update typings for mypy 1.6 [#229](https://github.com/jupyter/terminado/pull/229) ([@blink1073](https://github.com/blink1073)) - chore: update pre-commit hooks [#228](https://github.com/jupyter/terminado/pull/228) ([@pre-commit-ci](https://github.com/pre-commit-ci)) - Bump actions/checkout from 3 to 4 [#227](https://github.com/jupyter/terminado/pull/227) ([@dependabot](https://github.com/dependabot)) - Adopt sp-repo-review [#226](https://github.com/jupyter/terminado/pull/226) ([@blink1073](https://github.com/blink1073)) - Use local coverage [#220](https://github.com/jupyter/terminado/pull/220) ([@blink1073](https://github.com/blink1073)) - Clean up license file [#217](https://github.com/jupyter/terminado/pull/217) ([@dcsaba89](https://github.com/dcsaba89)) - Add more linting [#215](https://github.com/jupyter/terminado/pull/215) ([@blink1073](https://github.com/blink1073)) - Add docstring enforcement [#213](https://github.com/jupyter/terminado/pull/213) ([@blink1073](https://github.com/blink1073)) - Adopt ruff and address lint [#212](https://github.com/jupyter/terminado/pull/212) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-12-05&to=2023-11-10&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-12-05..2023-11-10&type=Issues) | [@dcsaba89](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Adcsaba89+updated%3A2022-12-05..2023-11-10&type=Issues) | [@dependabot](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Adependabot+updated%3A2022-12-05..2023-11-10&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Apre-commit-ci+updated%3A2022-12-05..2023-11-10&type=Issues) ## 0.17.1 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.17.0...f1221f46a692ff0bab0820395b008d4473269d3e)) ### Bugs fixed - Don't split manually on linebreaks [#209](https://github.com/jupyter/terminado/pull/209) ([@incase](https://github.com/incase)) ### Maintenance and upkeep improvements - Docs and workflow cleanup [#206](https://github.com/jupyter/terminado/pull/206) ([@blink1073](https://github.com/blink1073)) - CI Cleanup [#204](https://github.com/jupyter/terminado/pull/204) ([@blink1073](https://github.com/blink1073)) - Add ability to release from repo [#202](https://github.com/jupyter/terminado/pull/202) ([@blink1073](https://github.com/blink1073)) - Bump actions/checkout from 2 to 3 [#201](https://github.com/jupyter/terminado/pull/201) ([@dependabot](https://github.com/dependabot)) - Add dependabot [#200](https://github.com/jupyter/terminado/pull/200) ([@blink1073](https://github.com/blink1073)) ### Documentation improvements - Docs and workflow cleanup [#206](https://github.com/jupyter/terminado/pull/206) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-10-25&to=2022-12-05&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-10-25..2022-12-05&type=Issues) | [@dependabot](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Adependabot+updated%3A2022-10-25..2022-12-05&type=Issues) | [@incase](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aincase+updated%3A2022-10-25..2022-12-05&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Apre-commit-ci+updated%3A2022-10-25..2022-12-05&type=Issues) ## 0.17.0 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.16.0...91320b53ededce0ea507e1cd45b47492c085cac2)) ### Maintenance and upkeep improvements - Clean up docs install [#198](https://github.com/jupyter/terminado/pull/198) ([@blink1073](https://github.com/blink1073)) - Maintenance cleanup [#196](https://github.com/jupyter/terminado/pull/196) ([@blink1073](https://github.com/blink1073)) - Maintenance cleanup [#195](https://github.com/jupyter/terminado/pull/195) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-09-29&to=2022-10-25&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-09-29..2022-10-25&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Apre-commit-ci+updated%3A2022-09-29..2022-10-25&type=Issues) ## 0.16.0 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.15.0...7210e82a94596d7d8a00577169c09198efbe4633)) ### Bugs fixed - Fix issue where large stdin writes can cause Tornado to hang [#189](https://github.com/jupyter/terminado/pull/189) ([@KoopaKing](https://github.com/KoopaKing)) ### Maintenance and upkeep improvements - Switch to using hatch version [#186](https://github.com/jupyter/terminado/pull/186) ([@blink1073](https://github.com/blink1073)) - Fix flake8 v5 compat [#179](https://github.com/jupyter/terminado/pull/179) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-05-16&to=2022-09-29&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-05-16..2022-09-29&type=Issues) | [@KoopaKing](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3AKoopaKing+updated%3A2022-05-16..2022-09-29&type=Issues) | [@pre-commit-ci](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Apre-commit-ci+updated%3A2022-05-16..2022-09-29&type=Issues) ## 0.15.0 No merged PRs ## 0.13.3 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.13.2...2cccad61af7e7ec88e4db769664d8814985179d4)) ### Bugs fixed - Test ConPTY backend against pywinpty 2.0.5 [#146](https://github.com/jupyter/terminado/pull/146) ([@andfoy](https://github.com/andfoy)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-03-03&to=2022-03-07&type=c)) [@andfoy](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aandfoy+updated%3A2022-03-03..2022-03-07&type=Issues) | [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-03-03..2022-03-07&type=Issues) ## 0.13.2 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.13.1...9db93006a960bc90c3cc6b3f53b5cba1251b5071)) ### Bugs fixed - Increase scrollback to 1000 [#143](https://github.com/jupyter/terminado/pull/143) ([@yusufbashi](https://github.com/yusufbashi)) ### Maintenance and upkeep improvements - Add test for terminating the terminals and fix Windows terminal shutdown behavior [#142](https://github.com/jupyter/terminado/pull/142) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-01-27&to=2022-03-03&type=c)) [@andfoy](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aandfoy+updated%3A2022-01-27..2022-03-03&type=Issues) | [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-01-27..2022-03-03&type=Issues) | [@fcollonval](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Afcollonval+updated%3A2022-01-27..2022-03-03&type=Issues) | [@Wh1isper](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3AWh1isper+updated%3A2022-01-27..2022-03-03&type=Issues) | [@yusufbashi](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ayusufbashi+updated%3A2022-01-27..2022-03-03&type=Issues) ## 0.13.1 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.13.0...b522de5796e56c98a74918873ff453f828fb123e)) ### Maintenance and upkeep improvements - python_requires is an option in setup.cfg [#140](https://github.com/jupyter/terminado/pull/140) ([@minrk](https://github.com/minrk)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-01-27&to=2022-01-27&type=c)) [@minrk](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aminrk+updated%3A2022-01-27..2022-01-27&type=Issues) ## 0.13.0 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.12.4...d663c886bf39880585f97a2f46e28c3d368ea0f3)) ### Enhancements made - Add pre_pty_read_hook in pty_read [#136](https://github.com/jupyter/terminado/pull/136) ([@Wh1isper](https://github.com/Wh1isper)) ### Maintenance and upkeep improvements - Officially drop support for python 3.6 [#137](https://github.com/jupyter/terminado/pull/137) ([@blink1073](https://github.com/blink1073)) - Fix even more setup.cfg formatting [#134](https://github.com/jupyter/terminado/pull/134) ([@blink1073](https://github.com/blink1073)) - Fix more setup.cfg formatting [#133](https://github.com/jupyter/terminado/pull/133) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-01-26&to=2022-01-27&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-01-26..2022-01-27&type=Issues) | [@Wh1isper](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3AWh1isper+updated%3A2022-01-26..2022-01-27&type=Issues) ## 0.12.4 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.12.3...335e59d6e6c6574d2f0b48360dac9680faeeaa1a)) ### Maintenance and upkeep improvements - Fix formatting of trove classifiers again [#131](https://github.com/jupyter/terminado/pull/131) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-01-26&to=2022-01-26&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-01-26..2022-01-26&type=Issues) ## 0.12.3 ([Full Changelog](https://github.com/jupyter/terminado/compare/v0.12.2...d0510462c73663790bdb0ae87640b7565866d1f9)) ### Bugs fixed - Fix terminal output logging type error [#122](https://github.com/jupyter/terminado/pull/122) ([@devmonkey22](https://github.com/devmonkey22)) ### Maintenance and upkeep improvements - Fix formatting of trove classifiers [#129](https://github.com/jupyter/terminado/pull/129) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2022-01-26&to=2022-01-26&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2022-01-26..2022-01-26&type=Issues) | [@devmonkey22](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Adevmonkey22+updated%3A2022-01-26..2022-01-26&type=Issues) ## 0.12.2 ([Full Changelog](https://github.com/jupyter/terminado/compare/0.12.1...eea43b51a25be52e2e53334f94a5005a22d12109)) ### Bugs fixed - Use read_buffer for reconnect and remove preopen_buffer [#127](https://github.com/jupyter/terminado/pull/127) ([@Wh1isper](https://github.com/Wh1isper)) ### Maintenance and upkeep improvements - Run CI Daily [#125](https://github.com/jupyter/terminado/pull/125) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2021-09-07&to=2022-01-26&type=c)) [@andfoy](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aandfoy+updated%3A2021-09-07..2022-01-26&type=Issues) | [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2021-09-07..2022-01-26&type=Issues) | [@Wh1isper](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3AWh1isper+updated%3A2021-09-07..2022-01-26&type=Issues) ## 0.12.1 ([Full Changelog](https://github.com/jupyter/terminado/compare/0.12.0...a70e0bf98a597ce4d1ac5aa6915e70cf6e00789e)) ### Bugs fixed - Revert "only override TERM if its not previously set" [#119](https://github.com/jupyter/terminado/pull/119) ([@rvalieris](https://github.com/rvalieris)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2021-09-07&to=2021-09-07&type=c)) [@rvalieris](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Arvalieris+updated%3A2021-09-07..2021-09-07&type=Issues) ## 0.12.0 ([Full Changelog](https://github.com/jupyter/terminado/compare/0.11.1...89425f34beb639eb10d7534cf8ce789d18f22c71)) ### Bugs fixed - correctly set the TERM variable [#117](https://github.com/jupyter/terminado/pull/117) ([@rvalieris](https://github.com/rvalieris)) ### Maintenance and upkeep improvements - Replace deprecated unittest aliases [#116](https://github.com/jupyter/terminado/pull/116) ([@hugovk](https://github.com/hugovk)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2021-08-18&to=2021-09-07&type=c)) [@hugovk](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ahugovk+updated%3A2021-08-18..2021-09-07&type=Issues) | [@rvalieris](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Arvalieris+updated%3A2021-08-18..2021-09-07&type=Issues) ## 0.11.1 ([Full Changelog](https://github.com/jupyter/terminado/compare/0.11.0...0fa5a0cb9cc3b622457b492759998686cb83b10a)) ### Maintenance and upkeep improvements - Clean up tests [#114](https://github.com/jupyter/terminado/pull/114) ([@blink1073](https://github.com/blink1073)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2021-08-12&to=2021-08-18&type=c)) [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2021-08-12..2021-08-18&type=Issues) ## 0.11.0 ([Full Changelog](https://github.com/jupyter/terminado/compare/0.10.1...baa26d500a3836ba8835b6c674e60ddf0e79295e)) ### Enhancements made - Log terminal output [#112](https://github.com/jupyter/terminado/pull/112) ([@OmriShiv](https://github.com/OmriShiv)) ### Bugs fixed - Switch select() to poll() in pty_read() [#111](https://github.com/jupyter/terminado/pull/111) ([@arjanvandervelde](https://github.com/arjanvandervelde)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2021-06-10&to=2021-08-12&type=c)) [@arjanvandervelde](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aarjanvandervelde+updated%3A2021-06-10..2021-08-12&type=Issues) | [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2021-06-10..2021-08-12&type=Issues) | [@OmriShiv](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3AOmriShiv+updated%3A2021-06-10..2021-08-12&type=Issues) ## 0.10.1 ([Full Changelog](https://github.com/jupyter/terminado/compare/0.10.0...ada2b93a57bd0ebfae87d75b7561e2cd53ba598f)) ### Bugs fixed - Fix blocking of pty_read when there isn't pty data ready to read [#107](https://github.com/jupyter/terminado/pull/107) ([@icankeep](https://github.com/icankeep)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2021-05-18&to=2021-06-10&type=c)) [@icankeep](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aicankeep+updated%3A2021-05-18..2021-06-10&type=Issues) ## 0.10.0 ([Full Changelog](https://github.com/jupyter/terminado/compare/0.9.5...fbba87e45daa65029ad58a88b63384bffbf29937)) ### Enhancements made - Support creating terminal given name in kwargs. [#104](https://github.com/jupyter/terminado/pull/104) ([@cailiang9](https://github.com/cailiang9)) ### Bugs fixed - avoid persistent handle on IOLoop instance [#102](https://github.com/jupyter/terminado/pull/102) ([@minrk](https://github.com/minrk)) ### Maintenance and upkeep improvements - async/await syntax [#103](https://github.com/jupyter/terminado/pull/103) ([@minrk](https://github.com/minrk)) - PR: Pin pywinpty version to 1.1.0 [#101](https://github.com/jupyter/terminado/pull/101) ([@andfoy](https://github.com/andfoy)) ### Contributors to this release ([GitHub contributors page for this release](https://github.com/jupyter/terminado/graphs/contributors?from=2021-05-11&to=2021-05-18&type=c)) [@andfoy](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aandfoy+updated%3A2021-05-11..2021-05-18&type=Issues) | [@blink1073](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Ablink1073+updated%3A2021-05-11..2021-05-18&type=Issues) | [@cailiang9](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Acailiang9+updated%3A2021-05-11..2021-05-18&type=Issues) | [@minrk](https://github.com/search?q=repo%3Ajupyter%2Fterminado+involves%3Aminrk+updated%3A2021-05-11..2021-05-18&type=Issues) ## 0.9.5 - Pin pywinpty version [#98](https://github.com/jupyter/terminado/pull/98) ([@jtpio](https://github.com/jtpio)) ## 0.9.4 - Allow non-strict decode for process output [#95](https://github.com/jupyter/terminado/pull/95) ([@dong-zeyu](https://github.com/dong-zeyu)) - Switch to GitHub Actions [#93](https://github.com/jupyter/terminado/pull/93) ([@afshin](https://github.com/afshin)) - Add generated changelog [#92](https://github.com/jupyter/terminado/pull/92) ([@blink1073](https://github.com/blink1073)) ## 0.9.3 - Make sure SIGPIPE has default handler set [#91](https://github.com/jupyter/terminado/pull/91) ([@dlukes](https://github.com/dlukes)) ## 0.9.2 - Add js files in package manifest [#87](https://github.com/jupyter/terminado/pull/87) ([@MircoT](https://github.com/MircoT)) - Add support to ppc64le [#86](https://github.com/jupyter/terminado/pull/86) ([@gururajrkatti](https://github.com/gururajrkatti)) - Fix config files for publication [#81](https://github.com/jupyter/terminado/pull/81) ([@afshin](https://github.com/afshin)) ## 0.9.1 - v0.9.1 [#80](https://github.com/jupyter/terminado/pull/80) ([@afshin](https://github.com/afshin)) ## 0.9.0 - Drop python 2 and 3.4 and 3.5 support [#77](https://github.com/jupyter/terminado/pull/77) ([@jasongrout](https://github.com/jasongrout)) - Make sure that all process output makes it to the terminal [#76](https://github.com/jupyter/terminado/pull/76) ([@athornton](https://github.com/athornton)) ## v0.8.3 - Add kwargs to NamedTermManager.new_named_terminal [#70](https://github.com/jupyter/terminado/pull/70) ([@qntnrbns](https://github.com/qntnrbns)) ## 0.8.2 - Run only the basic test on Appveyor [#64](https://github.com/jupyter/terminado/pull/64) ([@blink1073](https://github.com/blink1073)) - Fix for https://github.com/jupyter/terminado/issues/62 [#63](https://github.com/jupyter/terminado/pull/63) ([@cpranav](https://github.com/cpranav)) - Add python_requires to help pip, and version classifiers [#57](https://github.com/jupyter/terminado/pull/57) ([@hugovk](https://github.com/hugovk)) - Set websocket.terminal to None when the child exits [#55](https://github.com/jupyter/terminado/pull/55) ([@takluyver](https://github.com/takluyver)) ## 0.8.1 - Add support for Python 2 on Windows [#50](https://github.com/jupyter/terminado/pull/50) ([@blink1073](https://github.com/blink1073)) - Update ownership [#48](https://github.com/jupyter/terminado/pull/48) ([@blink1073](https://github.com/blink1073)) ## 0.8 - Add support for Windows [#44](https://github.com/jupyter/terminado/pull/44) ([@blink1073](https://github.com/blink1073)) ## 0.7 - Reduce duplication in PtyWithClients.terminate [#43](https://github.com/jupyter/terminado/pull/43) ([@srstevenson](https://github.com/srstevenson)) - Pass signal to terminal from manager method [#42](https://github.com/jupyter/terminado/pull/42) ([@srstevenson](https://github.com/srstevenson)) - Send SIGHUP to the process group in the terminal, not just the leader [#38](https://github.com/jupyter/terminado/pull/38) ([@takluyver](https://github.com/takluyver)) - Include LICENSE.txt file in the tarball [#34](https://github.com/jupyter/terminado/pull/34) ([@irushchyshyn](https://github.com/irushchyshyn)) - Add requirements and README for demos [#31](https://github.com/jupyter/terminado/pull/31) ([@stuaxo](https://github.com/stuaxo)) - Revert pinging implementation, and call super method in websocket open [#28](https://github.com/jupyter/terminado/pull/28) ([@takluyver](https://github.com/takluyver)) - keep websocket connection alive by sending pings when there is no activity [#27](https://github.com/jupyter/terminado/pull/27) ([@zyzhu2000](https://github.com/zyzhu2000)) ## 0.6 - require tornado 4 [#26](https://github.com/jupyter/terminado/pull/26) ([@minrk](https://github.com/minrk)) - Close PtyProcess object instead of closing fd directly [#24](https://github.com/jupyter/terminado/pull/24) ([@takluyver](https://github.com/takluyver)) - use tornado's check_origin method name [#20](https://github.com/jupyter/terminado/pull/20) ([@minrk](https://github.com/minrk)) - Change `_log` -> `_logger`. [#19](https://github.com/jupyter/terminado/pull/19) ([@mgmarino](https://github.com/mgmarino)) - Make built wheels universal. [#14](https://github.com/jupyter/terminado/pull/14) ([@aragilar](https://github.com/aragilar)) ## 0.5 - Fix bugs when max_terminals reached, with test cases [#11](https://github.com/jupyter/terminado/pull/11) ([@payne92](https://github.com/payne92)) - More liberal read time out to address Travis CI test issues [#10](https://github.com/jupyter/terminado/pull/10) ([@payne92](https://github.com/payne92)) - More unit tests [#8](https://github.com/jupyter/terminado/pull/8) ([@payne92](https://github.com/payne92)) ## 0.4 - Initial unit test framework [#6](https://github.com/jupyter/terminado/pull/6) ([@payne92](https://github.com/payne92)) - Buffer the last 10 reads from the pty, and play back to new clients [#5](https://github.com/jupyter/terminado/pull/5) ([@takluyver](https://github.com/takluyver)) ## 0.3.2 - add async terminate method [#3](https://github.com/jupyter/terminado/pull/3) ([@minrk](https://github.com/minrk)) terminado-0.18.1/CONTRIBUTING.rst000066400000000000000000000057021457406376300162470ustar00rootroot00000000000000General Jupyter contributor guidelines ====================================== If you're reading this section, you're probably interested in contributing to Jupyter. Welcome and thanks for your interest in contributing! Please take a look at the Contributor documentation, familiarize yourself with using the ``terminado``, and introduce yourself on the mailing list and share what area of the project you are interested in working on. For general documentation about contributing to Jupyter projects, see the `Project Jupyter Contributor Documentation`__. __ https://jupyter.readthedocs.io/en/latest/contributing/content-contributor.html Setting Up a Development Environment ==================================== Installing Terminado -------------------- Run the the following steps to set up a local development environment:: pip install --upgrade setuptools pip git clone https://github.com/jupyter/terminado cd terminado pip install -e ".[test]" If you are using a system-wide Python installation and you only want to installed for you, you can add ``--user`` to the install commands. Code Styling ----------------------------- ``terminado`` has adopted automatic code formatting so you shouldn't need to worry too much about your code style. As long as your code is valid, the pre-commit hook should take care of how it should look. ``pre-commit`` and its associated hooks will automatically be installed when you run ``pip install -e ".[test]"`` To install ``pre-commit`` manually, run the following:: pip install pre-commit pre-commit install You can invoke the pre-commit hook by hand at any time with:: pre-commit run which should run any autoformatting on your code and tell you about any errors it couldn't fix automatically. You may also install [black integration](https://github.com/psf/black#editor-integration) into your text editor to format code automatically. If you have already committed files before setting up the pre-commit hook with ``pre-commit install``, you can fix everything up using ``pre-commit run --all-files``. You need to make the fixing commit yourself after that. Running Tests ============= Install dependencies:: pip install -e .[test] To run the Python tests, use:: pytest Building the Docs ================= To build the docs, run the following:: cd doc pip install -r requirements.txt make html .. _conda environment: https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-from-an-environment-yml-file After that, the generated HTML files will be available at ``build/html/index.html``. You may view the docs in your browser. You can automatically check if all hyperlinks are still valid:: make linkcheck Windows users can find ``make.bat`` in the ``docs`` folder. You should also have a look at the `Project Jupyter Documentation Guide`__. __ https://jupyter.readthedocs.io/en/latest/contributing/content-contributor.html terminado-0.18.1/LICENSE000066400000000000000000000025711457406376300146140ustar00rootroot00000000000000BSD 2-Clause 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 HOLDER 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.18.1/README.md000066400000000000000000000057601457406376300150710ustar00rootroot00000000000000# Terminado [![Build Status](https://github.com/jupyter/terminado/actions/workflows/test.yml/badge.svg?query=branch%3Amain++)](https://github.com/jupyter/terminado/actions/workflows/test.yml/badge.svg?query=branch%3Amain++) [![Documentation Status](https://readthedocs.org/projects/terminado/badge/?version=latest)](http://terminado.readthedocs.io/en/latest/?badge=latest) This is a [Tornado](http://tornadoweb.org/) websocket backend for the [Xterm.js](https://xtermjs.org/) Javascript terminal emulator library. It evolved out of [pyxterm](https://github.com/mitotic/pyxterm), which was part of [GraphTerm](https://github.com/mitotic/graphterm) (as lineterm.py), v0.57.0 (2014-07-18), and ultimately derived from the public-domain [Ajaxterm](http://antony.lesuisse.org/software/ajaxterm/) code, v0.11 (2008-11-13) (also on Github as part of [QWeb](https://github.com/antonylesuisse/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](http://www.tornadoweb.org/en/stable/guide/templates.html#ui-modules). JS: - `terminado/_static/terminado.js`: A lightweight wrapper to set up a term.js terminal with a websocket. Local Installation: > $ pip install -e .\[test\] Usage example: ```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](https://github.com/takluyver/terminado/tree/master/demos) for more examples. This is a simplified version of the `single.py` demo. Run the unit tests with: > $ pytest terminado-0.18.1/RELEASE.md000066400000000000000000000010351457406376300152030ustar00rootroot00000000000000The recommended way to make a release is to use [`jupyter_releaser`](https://jupyter-releaser.readthedocs.io/en/latest/get_started/making_release_from_repo.html). To create a manual release, update the version number in `terminado/__init__.py`, then run the following: ``` git clean -dffx pip install pipx pipx run build export script_version=`pipx run hatch version 2>/dev/null` git commit -a -m "Release $script_version" git tag $script_version git push --all git push --tags pipx run twine check dist/* pipx run twine upload dist/* ``` terminado-0.18.1/demos/000077500000000000000000000000001457406376300147115ustar00rootroot00000000000000terminado-0.18.1/demos/README.md000066400000000000000000000005471457406376300161760ustar00rootroot00000000000000# Demos ## 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.18.1/demos/common_demo_stuff.py000066400000000000000000000007711457406376300207730ustar00rootroot00000000000000import webbrowser from pathlib import Path import tornado.ioloop import terminado HERE = Path(terminado.__file__).parent STATIC_DIR = HERE / "_static" TEMPLATE_DIR = HERE / "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") # noqa: T201 finally: term_manager.shutdown() loop.close() terminado-0.18.1/demos/custom_exec.py000066400000000000000000000025541457406376300176070ustar00rootroot00000000000000"""Using a custom thread pool for subprocess writes. """ from concurrent import futures import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from common_demo_stuff import STATIC_DIR, TEMPLATE_DIR, run_and_show_browser from terminado import SingleTermManager, TermSocket 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): with futures.ThreadPoolExecutor(max_workers=2) as custom_exec: term_manager = SingleTermManager(shell_command=["bash"], blocking_io_executor=custom_exec) 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.18.1/demos/named.py000066400000000000000000000032421457406376300163500ustar00rootroot00000000000000"""One shared terminal per URL endpoint Plus a /new URL which will create a new terminal and redirect to it. """ import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from common_demo_stuff import STATIC_DIR, TEMPLATE_DIR, run_and_show_browser from terminado import NamedTermManager, TermSocket 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.18.1/demos/requirements.txt000066400000000000000000000000721457406376300201740ustar00rootroot00000000000000terminado tornado tornado-xstatic XStatic XStatic-term.js terminado-0.18.1/demos/single.py000066400000000000000000000022521457406376300165450ustar00rootroot00000000000000"""A single common terminal for all websockets. """ import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from common_demo_stuff import STATIC_DIR, TEMPLATE_DIR, run_and_show_browser from terminado import SingleTermManager, TermSocket 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.18.1/demos/templates/000077500000000000000000000000001457406376300167075ustar00rootroot00000000000000terminado-0.18.1/demos/templates/termpage.html000066400000000000000000000050371457406376300214060ustar00rootroot00000000000000 pyxterm
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0
1
2
3

terminado-0.18.1/demos/templates/uimod.html000066400000000000000000000012521457406376300207120ustar00rootroot00000000000000 Terminado UIModule demo

Terminado UIModule terminal

{% module Terminal("/websocket") %}
terminado-0.18.1/demos/uimod.py000066400000000000000000000023451457406376300164040ustar00rootroot00000000000000"""A single common terminal for all websockets. """ import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from common_demo_stuff import STATIC_DIR, TEMPLATE_DIR, run_and_show_browser from terminado import SingleTermManager, TermSocket, uimodule 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.18.1/demos/unique.py000066400000000000000000000022551457406376300165750ustar00rootroot00000000000000"""A separate terminal for every websocket opened. """ import tornado.web # This demo requires tornado_xstatic and XStatic-term.js import tornado_xstatic from common_demo_stuff import STATIC_DIR, TEMPLATE_DIR, run_and_show_browser from terminado import TermSocket, UniqueTermManager 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.18.1/doc/000077500000000000000000000000001457406376300143475ustar00rootroot00000000000000terminado-0.18.1/doc/Makefile000066400000000000000000000151661457406376300160200ustar00rootroot00000000000000# 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.18.1/doc/conf.py000066400000000000000000000206421457406376300156520ustar00rootroot00000000000000# # 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 shutil import sys from pathlib import Path HERE = Path(__file__).parent.resolve() sys.path.insert(0, HERE.parent) # 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 osp.abspath to make it absolute, like shown here. # sys.path.insert(0, osp.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 = [ "myst_parser", "sphinx.ext.autodoc", "sphinx.ext.intersphinx", ] # The master toctree document. master_doc = "index" # General information about the project. project = "Terminado" copyright = "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. # # Get information from _version.py and use it to generate version and release _version_py = HERE / "../terminado/_version.py" version_ns: dict = {} with _version_py.open() as fid: exec(compile(fid.read(), _version_py, "exec"), version_ns) # noqa: S102 # The short X.Y version. version = "{}.{}".format(*tuple(version_ns["__version__"].split(".")[:2])) # The full version, including alpha/beta/rc tags. release = version_ns["__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 = "pydata_sphinx_theme" # 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 = {"navigation_with_keys": False} # 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: dict = {} # 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", "Terminado Documentation", "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", "Terminado Documentation", ["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", "Terminado Documentation", "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)} def setup(app): dest = HERE / "changelog.md" shutil.copy(HERE / ".." / "CHANGELOG.md", dest) terminado-0.18.1/doc/index.rst000066400000000000000000000005731457406376300162150ustar00rootroot00000000000000Terminado ========= Contents: .. toctree:: :maxdepth: 1 websocket uimodule changelog .. seealso:: `Connecting Xterm.js to Terminado `_ From the Xterm.js docs .. include:: ../README.md :parser: myst_parser.sphinx_ Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` terminado-0.18.1/doc/uimodule.rst000066400000000000000000000020051457406376300167210ustar00rootroot00000000000000Using 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.18.1/doc/websocket.rst000066400000000000000000000044411457406376300170720ustar00rootroot00000000000000Using 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.18.1/pyproject.toml000066400000000000000000000106601457406376300165210ustar00rootroot00000000000000[build-system] requires = ["hatchling>=1.5"] build-backend = "hatchling.build" [project] name = "terminado" dynamic = ["version"] readme = "README.md" license = { file = "LICENSE" } description = "Tornado websocket backend for the Xterm.js Javascript terminal emulator library." classifiers = [ "Environment :: Web Environment", "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3", "Topic :: Terminals :: Terminal Emulators/X Terminals",] requires-python = ">=3.8" dependencies = [ "ptyprocess;os_name!='nt'", "pywinpty>=1.1.0;os_name=='nt'", "tornado>=6.1.0",] [[project.authors]] name = "Jupyter Development Team" email = "jupyter@googlegroups.com" [project.urls] Homepage = "https://github.com/jupyter/terminado" [project.optional-dependencies] test = [ "pytest>=7.0", "pre-commit", "pytest-timeout",] docs = [ "sphinx", "pydata-sphinx-theme", "myst_parser"] typing = ["mypy~=1.6", "traitlets>=5.11.1"] [tool.hatch.version] path = "terminado/_version.py" [tool.hatch.envs.docs] features = ["docs"] [tool.hatch.envs.docs.scripts] build = "make -C doc html SPHINXOPTS='-W'" [tool.hatch.envs.test] features = ["test"] [tool.hatch.envs.test.scripts] test = "python -m pytest -vv {args}" nowarn = "test -W default {args}" [tool.hatch.envs.cov] features = ["test"] dependencies = ["coverage", "pytest-cov"] [tool.hatch.envs.cov.scripts] test = "python -m pytest -vv --cov terminado --cov-branch --cov-report term-missing:skip-covered {args}" nowarn = "test -W default {args}" [tool.hatch.envs.lint] detached = true dependencies = ["pre-commit"] [tool.hatch.envs.lint.scripts] build = [ "pre-commit run --all-files ruff", "pre-commit run --all-files ruff-format" ] [tool.hatch.envs.typing] dependencies = [ "pre-commit"] detached = true [tool.hatch.envs.typing.scripts] test = "pre-commit run --all-files --hook-stage manual mypy" [tool.pytest.ini_options] minversion = "6.0" xfail_strict = true log_cli_level = "info" addopts = [ "-ra", "--durations=10", "--color=yes", "--doctest-modules", "--showlocals", "--strict-markers", "--strict-config" ] testpaths = [ "tests/" ] timeout = 300 filterwarnings = [ "error", "module:unclosed # Distributed under the terms of the Simplified BSD License. from ._version import __version__ # noqa: F401 from .management import ( NamedTermManager, # noqa: F401 SingleTermManager, # noqa: F401 TermManagerBase, # noqa: F401 UniqueTermManager, # noqa: F401 ) from .websocket import TermSocket # noqa: F401 terminado-0.18.1/terminado/_static/000077500000000000000000000000001457406376300172125ustar00rootroot00000000000000terminado-0.18.1/terminado/_static/terminado.js000066400000000000000000000021321457406376300215300ustar00rootroot00000000000000// 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.18.1/terminado/_version.py000066400000000000000000000000711457406376300177600ustar00rootroot00000000000000"""Version info for terminado.""" __version__ = "0.18.1" terminado-0.18.1/terminado/management.py000066400000000000000000000370141457406376300202570ustar00rootroot00000000000000"""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 annotations import asyncio import codecs import itertools import logging import os import select import signal import warnings from collections import deque from concurrent import futures from typing import TYPE_CHECKING, Any, Coroutine if TYPE_CHECKING: from terminado.websocket import TermSocket try: from ptyprocess import PtyProcessUnicode # type:ignore[import-untyped] def preexec_fn() -> None: """A prexec function to set up a signal handler.""" signal.signal(signal.SIGPIPE, signal.SIG_DFL) except ImportError: try: from winpty import PtyProcess as PtyProcessUnicode # type:ignore[import-not-found] 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: """A pty object with associated clients.""" term_name: str | None def __init__(self, argv: Any, env: dict[str, str] | None = None, cwd: str | None = None): """Initialize the pty.""" self.clients: list[Any] = [] # Use read_buffer to store historical messages for reconnection self.read_buffer: deque[str] = deque([], maxlen=1000) kwargs = {"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) -> None: """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: int = signal.SIGTERM) -> None: """Send a signal to the process in the pty""" self.ptyproc.kill(sig) def killpg(self, sig: int = signal.SIGTERM) -> Any: """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) return None async def terminate(self, force: bool = False) -> bool: """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() -> Coroutine[Any, Any, None]: """Sleep to allow the terminal to exit gracefully.""" 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() return bool(not self.ptyproc.isalive()) 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() return bool(not self.ptyproc.isalive()) def _update_removing(target: Any, changes: Any) -> None: """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[tuple[int, int]]: """Poll using poll() on posix systems and select() elsewhere (e.g., Windows)""" if os.name == "posix": poller = select.poll() poller.register( fd, select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR ) # read-only return poller.poll(timeout * 1000) # milliseconds # 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: str, server_url: str = "", term_settings: Any = None, extra_env: Any = None, ioloop: Any = None, blocking_io_executor: Any = None, ): """Initialize the manager.""" 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: dict[int, PtyWithClients] = {} if blocking_io_executor is None: self._blocking_io_executor_is_external = False self.blocking_io_executor = futures.ThreadPoolExecutor(max_workers=1) else: self._blocking_io_executor_is_external = True self.blocking_io_executor = blocking_io_executor 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: int = 25, width: int = 80, winheight: int = 0, winwidth: int = 0, **kwargs: Any, ) -> dict[str, str]: """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: Any) -> PtyWithClients: """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: PtyWithClients) -> None: """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: PtyWithClients) -> None: """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: int, events: Any = None) -> 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("Spurious pty_read() on fd %s", 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: PtyWithClients) -> None: """Hook before pty read, subclass can patch something into ptywclients when pty_read""" def get_terminal(self, url_component: Any = None) -> PtyWithClients: """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: Any) -> None: """Override this to e.g. kill terminals on client disconnection.""" async def shutdown(self) -> None: """Shutdown the manager.""" await self.kill_all() if not self._blocking_io_executor_is_external: self.blocking_io_executor.shutdown(wait=False, cancel_futures=True) # type:ignore[call-arg] async def kill_all(self) -> None: """Kill all terminals.""" 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: Any) -> None: """Initialize the manager.""" super().__init__(**kwargs) self.terminal: PtyWithClients | None = None def get_terminal(self, url_component: Any = None) -> PtyWithClients: """ "Get the singleton terminal.""" if self.terminal is None: self.terminal = self.new_terminal() self.start_reading(self.terminal) return self.terminal async def kill_all(self) -> None: """Kill the singletone terminal.""" await super().kill_all() self.terminal = None class MaxTerminalsReached(Exception): """An error raised when we exceed the max number of terminals.""" def __init__(self, max_terminals: int) -> None: """Initialize the error.""" self.max_terminals = max_terminals def __str__(self) -> str: """The string representation of the error.""" 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: int | None = None, **kwargs: Any) -> None: """Initialize the manager.""" super().__init__(**kwargs) self.max_terminals = max_terminals def get_terminal(self, url_component: Any = None) -> PtyWithClients: """Get a terminal from the manager.""" 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: TermSocket) -> None: """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: Any = None, **kwargs: Any) -> None: """Initialize the manager.""" super().__init__(**kwargs) self.max_terminals = max_terminals self.terminals: dict[str, PtyWithClients] = {} def get_terminal(self, term_name: str) -> PtyWithClients: # type:ignore[override] """Get or create a terminal by 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) -> str | None: for n in itertools.count(start=1): name = self.name_template % n if name not in self.terminals: return name return None def new_named_terminal(self, **kwargs: Any) -> tuple[str, PtyWithClients]: """Create a new named terminal with an automatic name.""" name = kwargs["name"] if "name" in kwargs else 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: str, sig: int = signal.SIGTERM) -> None: """Kill a terminal by name.""" term = self.terminals[name] term.kill(sig) # This should lead to an EOF async def terminate(self, name: str, force: bool = False) -> None: """Terminate a terminal by name.""" term = self.terminals[name] await term.terminate(force=force) def on_eof(self, ptywclients: PtyWithClients) -> None: """Handle end of file for a pty with clients.""" super().on_eof(ptywclients) name = ptywclients.term_name self.log.info("Terminal %s closed", name) assert name is not None self.terminals.pop(name, None) async def kill_all(self) -> None: """Kill all terminals.""" await super().kill_all() self.terminals = {} terminado-0.18.1/terminado/py.typed000066400000000000000000000000001457406376300172510ustar00rootroot00000000000000terminado-0.18.1/terminado/uimod_embed.js000066400000000000000000000014211457406376300203710ustar00rootroot00000000000000// 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.18.1/terminado/uimodule.py000066400000000000000000000022701457406376300177620ustar00rootroot00000000000000"""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. from __future__ import annotations from pathlib import Path import tornado.web class Terminal(tornado.web.UIModule): """A terminal UI module.""" def render(self, ws_url: str, cols: int = 80, rows: int = 25) -> str: """Render the module.""" return ( '
' ) def javascript_files(self) -> list[str]: """Get the list of JS files to include.""" # TODO: Can we calculate these dynamically? return ["/xstatic/termjs/term.js", "/static/terminado.js"] def embedded_javascript(self) -> str: """Get the embedded JS content as a string.""" file = Path(__file__).parent / "uimod_embed.js" with file.open() as f: return f.read() terminado-0.18.1/terminado/websocket.py000066400000000000000000000126701457406376300201320ustar00rootroot00000000000000"""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 annotations import json import logging import os from typing import TYPE_CHECKING, Any import tornado.websocket from tornado import gen from tornado.concurrent import run_on_executor if TYPE_CHECKING: from terminado.management import PtyWithClients, TermManagerBase def _cast_unicode(s: str | bytes) -> str: 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: TermManagerBase) -> None: """Initialize the handler.""" self.term_manager = term_manager self.term_name = "" self.size = (None, None) self.terminal: PtyWithClients | None = None self._blocking_io_executor = term_manager.blocking_io_executor 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: str | None = None) -> bool: """Deprecated: backward-compat for terminado <= 0.5.""" origin = origin or self.request.headers.get("Origin", "") assert origin is not None return self.check_origin(origin) def open(self, url_component: Any = None) -> None: # type:ignore[override] """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: str) -> None: """Data read from pty; send to frontend""" self.send_json_message(["stdout", text]) def send_json_message(self, content: Any) -> None: """Send a json message on the socket.""" json_msg = json.dumps(content) self.write_message(json_msg) if self._enable_output_logging and content[0] == "stdout" and isinstance(content[1], str): self.log_terminal_output(f"STDOUT: {content[1]}") @gen.coroutine def on_message(self, message: str) -> None: # type:ignore[misc] """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": yield self.stdin_to_ptyproc(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) -> None: """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) -> None: """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) @run_on_executor(executor="_blocking_io_executor") def stdin_to_ptyproc(self, text: str) -> None: """Handles stdin messages sent on the websocket. This is a blocking call that should NOT be performed inside the server primary event loop thread. Messages must be handled asynchronously to prevent blocking on the PTY buffer. """ if self.terminal is not None: self.terminal.ptyproc.write(text) terminado-0.18.1/tests/000077500000000000000000000000001457406376300147445ustar00rootroot00000000000000terminado-0.18.1/tests/__init__.py000066400000000000000000000000001457406376300170430ustar00rootroot00000000000000terminado-0.18.1/tests/basic_test.py000066400000000000000000000267161457406376300174520ustar00rootroot00000000000000# 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. 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 >= (3, 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 ASYNC_TEST_TIMEOUT = 30 os.environ["ASYNC_TEST_TIMEOUT"] = str(ASYNC_TEST_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 discard_stdout(self, timeout=DONE_TIMEOUT): """Read standard output messages, discarding the data as it's received. Return the number of bytes discarded and any non-stdout msgs""" othermsg: list = [] bytes_discarded = 0 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 bytes_discarded, othermsg if msg[0] == "stdout": bytes_discarded += len(msg[1]) else: othermsg.append(msg) 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: # This should work on any OS, but keeping the above Windows special # case as I can't verify on Windows. for li in stdout.splitlines(): if re.match(r"\d+$", li): pid = int(li) break 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 [tm.close() for tm in tms] @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 tm.close() [tm.close() for tm in tms] 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 [tm.close() for tm in tms] 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]) [tm.close() for tm in tms] @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") tm.close() @tornado.testing.gen_test @pytest.mark.timeout(timeout=ASYNC_TEST_TIMEOUT, method="thread") async def test_large_io_doesnt_hang(self): # This is a regression test for an error where Terminado hangs when # the PTY buffer size is exceeded. While the buffer size varies from # OS to OS, 30KBish seems like a reasonable amount and will trigger # this on both OSX and Debian. massive_payload = "ten bytes " * 3000 massive_payload = "echo " + massive_payload + "\n" tm = await self.get_term_client("/unique") # Clear all startup messages. await tm.read_all_msg() # Write a payload that doesn't fit in a single PTY buffer. await tm.write_stdin(massive_payload) # Verify that the server didn't hang when responding, and that # we got a reasonable amount of data back (to tell us the read # didn't just timeout. bytes_discarded, other = await tm.discard_stdout() # Echo won't actually output anything on Windows. if "win" not in platform: assert bytes_discarded > 10000 assert other == [] tm.close() if __name__ == "__main__": unittest.main()