Skip to content
runpy 4.86 KiB
Newer Older
Andreas Klöckner's avatar
Andreas Klöckner committed
#! /usr/bin/env python3

# placate flake8
from __future__ import print_function
Andreas Klöckner's avatar
Andreas Klöckner committed

__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
Andreas Klöckner's avatar
Andreas Klöckner committed
import socketserver
import json
import sys
import io
Dong Zhuang's avatar
Dong Zhuang committed
try:
    from code_runpy_backend import Struct, run_code, package_exception
except ImportError:
    try:
        # When faking a container for unittest
        from course.page.code_runpy_backend import (
            Struct, run_code, package_exception)
    except ImportError:
        # When debugging, i.e., run "python runpy" command line
        import os
        sys.path.insert(0, os.path.abspath(
            os.path.join(os.path.dirname(__file__), os.pardir)))
        from course.page.code_runpy_backend import (
            Struct, run_code, package_exception)

from http.server import BaseHTTPRequestHandler
Andreas Klöckner's avatar
Andreas Klöckner committed

PORT = 9941
OUTPUT_LENGTH_LIMIT = 16*1024

TEST_COUNT = 0


def truncate_if_long(s):
    if len(s) > OUTPUT_LENGTH_LIMIT:
        s = s[:OUTPUT_LENGTH_LIMIT] + "[TRUNCATED... TOO MUCH OUTPUT]"
    return s
class RunRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print("GET RECEIVED", file=sys.stderr)
        if self.path != "/ping":
            raise RuntimeError("unrecognized path in GET")

        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()

        self.wfile.write(b"OK")
        print("PING RESPONSE DONE", file=sys.stderr)

        global TEST_COUNT
        TEST_COUNT += 1

        prev_stdout = sys.stdout  # noqa
        prev_stderr = sys.stderr  # noqa
Andreas Klöckner's avatar
Andreas Klöckner committed
        try:
            print("POST RECEIVED", file=prev_stderr)
            if self.path != "/run-python":
                raise RuntimeError("unrecognized path in POST")

            clength = int(self.headers['content-length'])
            recv_data = self.rfile.read(clength)

Andreas Klöckner's avatar
Andreas Klöckner committed
            print("RUNPY RECEIVED %d bytes" % len(recv_data),
            run_req = Struct(json.loads(recv_data.decode("utf-8")))
            print("REQUEST: %r" % run_req, file=prev_stderr)
Andreas Klöckner's avatar
Andreas Klöckner committed

            stdout = io.StringIO()
            stderr = io.StringIO()

            sys.stdin = None
            sys.stdout = stdout
            sys.stderr = stderr

            response["stdout"] = truncate_if_long(stdout.getvalue())
            response["stderr"] = truncate_if_long(stderr.getvalue())
            print("REQUEST SERVICED: %r" % response, file=prev_stderr)
            json_result = json.dumps(response).encode("utf-8")

            self.send_response(200)
            self.send_header("Content-type", "application/json")
            self.end_headers()

            print("WRITING RESPONSE", file=prev_stderr)
            self.wfile.write(json_result)
            print("WROTE RESPONSE", file=prev_stderr)
Andreas Klöckner's avatar
Andreas Klöckner committed
        except:
            print("ERROR RESPONSE", file=prev_stderr)
            response = {}
            package_exception(response, "uncaught_error")
            json_result = json.dumps(response).encode("utf-8")

            self.send_response(500)
            self.send_header("Content-type", "application/json")
            self.end_headers()
            self.wfile.write(json_result)
        finally:
            sys.stdout = prev_stdout
            sys.stderr = prev_stderr
    print("STARTING, LISTENING ON %d" % PORT, file=sys.stderr)
    server = socketserver.TCPServer(("", PORT), RunRequestHandler)

    serve_single_test = len(sys.argv) > 1 and sys.argv[1] == "-1"

    while True:
        server.handle_request()
        print("SERVED REQUEST", file=sys.stderr)
        if TEST_COUNT > 0 and serve_single_test:
            break

    server.server_close()
    print("FINISHED server_close()", file=sys.stderr)

    print("EXITING", file=sys.stderr)
Andreas Klöckner's avatar
Andreas Klöckner committed


if __name__ == "__main__":
    main()

# vim: foldmethod=marker