aboutsummaryrefslogtreecommitdiffstats
path: root/snekbox.py
blob: 4b9d726f5fffa282237f0cd634414d8832220f12 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import sys
import io
import json
import multiprocessing
import threading
import time

from logs import log
from rmq import Rmq

rmq = Rmq()


def execute(body):
    msg = body.decode('utf-8')
    log.info(f"incoming: {msg}")

    failed = False

    old_stdout = sys.stdout
    old_stderr = sys.stderr
    redirected_output = sys.stdout = io.StringIO()
    redirected_error = sys.stderr = io.StringIO()
    snek_msg = json.loads(msg)
    snekid = snek_msg['snekid']
    snekcode = snek_msg['message'].strip()

    try:
        exec(snekcode)

    except Exception as e:
        failed = str(e)

    finally:
        sys.stdout = old_stdout
        sys.stderr = old_stderr

    if failed:
        result = failed.strip()
        log.debug(f"this was captured via exception: {result}")

    result_err = redirected_error.getvalue().strip()
    result_ok = redirected_output.getvalue().strip()

    if result_err:
        log.debug(f"this was captured via stderr: {result_err}")
        result = result_err
    if result_ok:
        result = result_ok

    log.info(f"outgoing: {result}")

    rmq.publish(result,
                queue=snekid,
                routingkey=snekid,
                exchange=snekid)
    exit(0)

def stopwatch(process):
    log.debug(f"10 second timer started for process {process.pid}")
    for _ in range(10):
        time.sleep(1)
        if not process.is_alive():
            log.debug(f"Clean exit on process {process.pid}")
            exit(0)

    process.terminate()
    log.debug(f"Rerminated process {process.pid} forcefully")

def message_handler(ch, method, properties, body, thread_ws=None):
    p = multiprocessing.Process(target=execute, args=(body,))
    p.daemon = True
    p.start()

    t = threading.Thread(target=stopwatch, args=(p,))
    t.daemon = True
    t.start()

    ch.basic_ack(delivery_tag=method.delivery_tag)


if __name__ == '__main__':
    rmq.consume(callback=message_handler)